package com.mdd.controller;

import com.mdd.domain.Book;
import com.mdd.domain.Result;
import com.mdd.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;
    // 查询所有书本
    @GetMapping
    public Result selectAll(){
        System.out.println("selectAll is ok!");
        return Result.success(200,"查询成功！",bookService.selectAll());
    }

    // 添加书本
    @PostMapping
    public Result addBook(@RequestBody Book book){
        System.out.println("addBook is ok ===>"+book);
        Integer num = bookService.addBook(book);
        if(num >0) return Result.result(200,"添加成功！");
        return Result.result(404,"添加失败！");
    }

    // 根据ID查询书本
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        System.out.println("selectById is ok ===>"+id);
        Book book = bookService.selectById(id);
        if(book != null) return Result.success(200,"查询成功！",book);
        return Result.result(404,"查无此人！");
    }

    // 根据ID修改书本
    @PutMapping()
    public Result updateById(@RequestBody Book book){
        System.out.println("updateById is ok ===>"+book);
        Integer num = bookService.updateById(book);
        if(num >0) return Result.result(200,"修改成功！");
        return Result.result(404,"修改失败！");
    }

    // 根据ID删除书本
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        System.out.println("deleteById is ok ===>"+id);
        Integer num = bookService.deleteById(id);
        if(num >0) return Result.result(200,"删除成功！");
        return Result.result(404,"删除失败！");
    }
}
